﻿using FinancialManagement.Application.Command.ReceivableCommand;
using FinancialManagement.Domain.Dto;
using FinancialManagement.Domain.Model;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using SqlSugar;

namespace FinancialManagement.Application.CommandHandler.ReceivableCommandHandler
{

    /// <summary>
    /// 应收账款（直接付款）的添加
    /// </summary>
    public class AddReceivableCommandHandler : IRequestHandler<AddReceivableCommand, int>
    {

        IAccountReceivableRepository arRep;
        ISaleContractProductRepository scpRep;
        ISaleContractRepository scRep;
        ISqlSugarClient db;

        public AddReceivableCommandHandler(IAccountReceivableRepository arRep,
        ISaleContractProductRepository scpRep,
        ISaleContractRepository scRep,
        ISqlSugarClient db)
        {
            this.arRep = arRep;
            this.scpRep = scpRep;
            this.scRep = scRep;
            this.db = db;
        }

        public async Task<int> Handle(AddReceivableCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加
                var list = await arRep.AddAsync(new AccountReceivable
                {
                    ARNumber = Guid.NewGuid().ToString().Replace("-"," "),
                    AClientName = request.AClientName,
                    AReceivableAmount = request.AReceivableAmount,
                    APDocumentDate = request.APDocumentDate,
                    AReceivableWay = request.AReceivableWay,
                    AReceivableAccount = request.AReceivableAccount,
                });

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }



        }
    }
}
